<?php
if(!isset($_SESSION))
	session_start();
if(!isset($_SESSION["id"]))
{
	echo "Bạn chưa đăng nhập. Xin vui lòng đăng nhập hoặc nhấp vào <a href='?action=dangky'>Đây</a> để đăng ký";
	return;	
}
include "../connect.php";
include "../function.php";
include "thanhtien.php";
	$thanhvienid=$_SESSION["id"];
	$sanid=$_REQUEST['id'];
	$ngaybatdau=$_REQUEST['ngaybd'];
	$ngayketthuc=$_REQUEST['ngaykt'];
	$tgbatdau=substr($_REQUEST['thoigianbd'],0,2);
	$tgketthuc=substr($_REQUEST['thoigiankt'],0,2);
	$thu=isset($_REQUEST['thu'])?$_REQUEST['thu']:array();
	$thu=explode(",", $thu);
	$ArrThu= array("Hai"=>0, "Ba"=>0, "Tu"=>0, "Nam"=>0, "Sau"=>0, "Bay"=>0, "ChuNhat"=>0);
	mysql_query("START TRANSACTION");
	$SOID=taoma('PDS');
	$sql="insert into phieudatsan(phieudatsanno,thanhvienid,sanid) values('$SOID','$thanhvienid','$sanid')";
	$kq=mysql_query($sql);
	if(!$kq)
	{
		echo "2";			
	}
	else{
		$SoNgayCuaTuan=0;
		foreach($thu as $val)
		{
			$SoNgayCuaTuan++;
			$ArrThu[$val]=1;
		}
		$phieudatsanid=layid('phieudatsan');
		$ArrGioHoatDongID=LayThoiGianIDtuBangThoiGianHoatDong($tgbatdau,$tgketthuc);
		$demlichdatsan=0;
		$sqlsetma="set @maphieudatsan=last_insert_id()";
		$kqsetma=mysql_query($sqlsetma);
		for($k=0;$k<count($ArrGioHoatDongID);$k++)
		{
			//$SOItemID=taoma('LDS');
			$sqllich="INSERT INTO lichdatsan(PhieuDatSanID,GioHoatDongID,SoNgayCuaTuan,NgayBD,NgayKT,Hai,Ba,Tu,Nam,Sau,Bay,ChuNhat)
						VALUES (@maphieudatsan,'$ArrGioHoatDongID[$k]','$SoNgayCuaTuan','$ngaybatdau','$ngayketthuc',".
						$ArrThu["Hai"].",".$ArrThu["Ba"].",".$ArrThu["Tu"].",".$ArrThu["Nam"].",".$ArrThu["Sau"].",".$ArrThu["Bay"].",".$ArrThu["ChuNhat"].")";
			$kqlich=mysql_query($sqllich);
			if($kqlich)
				$demlichdatsan=1;
		}
		if($demlichdatsan==1)
		{
			mysql_query("COMMIT");
			thanhtien($phieudatsanid,$tienthue);
			$sqlthanhtien="Update phieudatsan set ThanhTien=$tienthue where PhieuDatSanID='$phieudatsanid'";
			$kq=mysql_query($sqlthanhtien);
			if($kq)
			{
				include "sendmail.php";
			}
			else
			{
				echo "3";
			}
		}
		else
			{
				mysql_query("ROLLBACK");
				echo "4";
			}
			
	}
?>